package com.zjj.lbw.algorithm.graph;

/**
 * @author zhanglei.zjj
 * @description leetcode_200. 岛屿数量，图解法实现
 * 给你一个由'1'（陆地）和 '0'（水）组成的的二维网格，请你计算网格中岛屿的数量。
 * <p>
 * 岛屿总是被水包围，并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
 * <p>
 * 此外，你可以假设该网格的四条边均被水包围。
 * <p>
 * <p>
 * <p>
 * 示例 1：
 * <p>
 * 输入：grid = [
 * ["1","1","1","1","0"],
 * ["1","1","0","1","0"],
 * ["1","1","0","0","0"],
 * ["0","0","0","0","0"]
 * ]
 * 输出：1
 * 示例 2：
 * <p>
 * 输入：grid = [
 * ["1","1","0","0","0"],
 * ["1","1","0","0","0"],
 * ["0","0","1","0","0"],
 * ["0","0","0","1","1"]
 * ]
 * 输出：3
 * <p>
 * <p>
 * 提示：
 * <p>
 * m == grid.length
 * n == grid[i].length
 * 1 <= m, n <= 300
 * grid[i][j] 的值为 '0' 或 '1'
 * @date 2023/6/23 21:57
 */
public class NumberofIslands_leetcode_200_graph {
    // 图论实现
    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0) {
            return 0;
        }

        int nr = grid.length;
        int nc = grid[0].length;
        int num_islands = 0;
        for (int row = 0; row < nr; ++row) {
            for (int col = 0; col < nc; ++col) {
                /*当前元素是岛屿，进行深度遍历搜索*/
                if (grid[row][col] == '1') {
                    ++num_islands;
                    dfs(grid, row, col);
                }
            }
        }

        return num_islands;
    }

    void dfs(char[][] grid, int row, int col) {
        int nr = grid.length;
        int nc = grid[0].length;

        /*访问越界检查*/
        if (row < 0 || col < 0 || row >= nr || col >= nc || grid[row][col] == '0') {
            return;
        }

        /*标识当前元素已经访问过了*/
        grid[row][col] = '0';
        /*往当前元素的上下左右去试探*/
        dfs(grid, row - 1, col);
        dfs(grid, row + 1, col);
        dfs(grid, row, col - 1);
        dfs(grid, row, col + 1);
    }
}
